package ubi.quando.UI;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import ubi.quando.App.Contact;
import ubi.quando.App.EventBase;
import ubi.quando.App.EventPickUp;
import ubi.quando.App.EventType;
import ubi.quando.App.PickUpParticipant;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class AddParticipantsPickUpActivity extends AddParticipantsBaseActivity {

	public static final String SerializePPU = "PPU";;
	public static final String SerializeAdded = "Added";;
	public static final String SerializeRemoved = "Removed";;

	static final int TIME_DIALOG_ID = 0;
	static final int DATE_DIALOG_ID = 1;

	private Map<Contact, PickUpParticipant> mAdded;
	private Map<Contact, PickUpParticipant> mRemoved;
	private PickUpParticipant mEditedParticipant;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mAdded = new HashMap<Contact, PickUpParticipant>();
		mRemoved = new HashMap<Contact, PickUpParticipant>();

		mListView.setVisibility(View.GONE);

		InvalidateTable();
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onResume() {
		super.onResume();
		mApp.setCurrentActivity(this);

		Bundle b = getIntent().getExtras();
		if (b != null) {
			mEvent = (EventPickUp) b.getSerializable(EventBase.SerializeName);

			if (b.getBoolean(SerializePPU)) {
				PickUpParticipant participant = (PickUpParticipant) b
						.getSerializable(PickUpParticipant.SerializeName);
				mAdded = (Map<Contact, PickUpParticipant>) b
						.getSerializable(AddParticipantsPickUpActivity.SerializeAdded);
				mAdded.put(mApp.getContactById(participant.getContact()), participant);  //TODO check it

				mRemoved = (Map<Contact, PickUpParticipant>) b
						.getSerializable(AddParticipantsPickUpActivity.SerializeRemoved);
			} else {
				Map<Contact, PickUpParticipant> awaiting = mEvent.getAwaiting();
				Iterator<Map.Entry<Contact, PickUpParticipant>> iter = awaiting
						.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry<Contact, PickUpParticipant> next = iter.next();
					mAdded.put(next.getKey(), next.getValue());
				}
				mRemoved.clear();
			}
		}

		InvalidateTable();
	}

	@Override
	protected void InitListeners() {
		mTextView.setOnItemClickListener(new ACOnItemClickListener());
		mOkBtn.setOnClickListener(new OkOnClickListener());
		mCancelBtn.setOnClickListener(new CancelOnClickListener());
	}

	private void InvalidateTable() {
		mTableView.removeAllViews();

		Iterator<Map.Entry<Contact, PickUpParticipant>> iter = mAdded
				.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry<Contact, PickUpParticipant> p = iter.next();
			TableRow row = new TableRow(this);
			TextView name = new TextView(this);
			name.setText(p.getKey().getName());
			name.setTextColor(ColorStateList.valueOf(-7829368));
			name.setOnClickListener(new TextOnClickListener());
			row.addView(name);
			row.setTag(p.getKey().getId());
			Button loc = new Button(this);
			loc.setText("loc");
			loc.setGravity(Gravity.RIGHT);
			loc.setOnClickListener(new LocOnClickListener());
			row.addView(loc);
			Button date = new Button(this);
			date.setText("date");
			date.setGravity(Gravity.RIGHT);
			date.setOnClickListener(new DateOnClickListener());
			row.addView(date);
			Button time = new Button(this);
			time.setText("time");
			time.setGravity(Gravity.RIGHT);
			time.setOnClickListener(new TimeOnClickListener());
			row.addView(time);

			mTableView.addView(row);
		}
	}

	public class ACOnItemClickListener implements OnItemClickListener {

		public void onItemClick(AdapterView<?> parent, View view, int pos,
				long id) {
			Contact contact = (Contact)parent.getItemAtPosition(pos);
			if (!mAdded.containsKey(contact)) {
				PickUpParticipant participant = new PickUpParticipant();
				participant.setContact(contact.getId());   //TODO check it
				participant.setDate(mEvent.GetDate());
				mAdded.put(contact, participant);
				mRemoved.remove(contact);
				InvalidateTable();
				Toast.makeText(getApplicationContext(),
						"Time & Date are set defaultly to the events data",
						Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(getApplicationContext(),
						"This participant is already in the list",
						Toast.LENGTH_LONG).show();
			}

			mTextView.setText("");
		}
	}

	public class OkOnClickListener implements OnClickListener {

		public void onClick(View v) {
			if (!IsDataValid()) {
				Toast.makeText(getApplicationContext(),
						"Location of some participant is not set",
						Toast.LENGTH_LONG).show();
				return;
			}

			Iterator<Map.Entry<Contact, PickUpParticipant>> iter = mAdded
					.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry<Contact, PickUpParticipant> c = iter.next();
				mEvent.AddInvited(c.getKey(), c.getValue());
			}

			iter = mRemoved.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry<Contact, PickUpParticipant> c = iter.next();
				mEvent.RemoveInvited(c.getKey());
			}

			Bundle b = new Bundle();
			b.putSerializable(EventBase.SerializeName, mEvent);
			Intent intent = new Intent(v.getContext(),
					ArrangeIPickUActivity.class);
			intent.putExtras(b);
			startActivity(intent);
		}

		private boolean IsDataValid() {
			Iterator<Map.Entry<Contact, PickUpParticipant>> iter = mAdded
					.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry<Contact, PickUpParticipant> c = iter.next();
				if (c.getValue().getLocation() == null) {
					return false;
				}
			}
			return true;
		}
	}

	public class CancelOnClickListener implements OnClickListener {

		public void onClick(View v) {
			Bundle b = new Bundle();
			b.putSerializable(EventBase.SerializeName, mEvent);
			Intent intent = new Intent(v.getContext(),
					ArrangeIPickUActivity.class);
			intent.putExtras(b);
			startActivity(intent);
		}
	}

	public class LocOnClickListener implements OnClickListener {

		public void onClick(View v) {
			TableRow row = (TableRow) v.getParent();
			Contact contact = mApp.getContactById((String)row.getTag());
			mEditedParticipant = mAdded.get(contact);

			Intent chooseLoc = new Intent(v.getContext(),
					ChooseLocationActivity.class);
			Bundle b = new Bundle();
			b.putBoolean("ChooseDestination", false);
			SetEventType(b);

			b.putBoolean(ArrangeEventBaseActivity.SerializeIsDest, false);
			b.putSerializable(EventBase.SerializeName, mEvent);
			b.putBoolean(SerializePPU, true);
			b.putSerializable(PickUpParticipant.SerializeName,
					mEditedParticipant);
			b.putSerializable(SerializeAdded,
					(HashMap<Contact, PickUpParticipant>) mAdded);
			b.putSerializable(SerializeRemoved,
					(HashMap<Contact, PickUpParticipant>) mRemoved);

			chooseLoc.putExtras(b);
			startActivity(chooseLoc);
		}

		private void SetEventType(Bundle b) {
			if (b != null) {
				EventType type = EventType.I_PICK_U;
				b.putInt(EventType.SerializeName, EventType.ToInt(type));
			}
		}
	}

	public class DateOnClickListener implements OnClickListener {

		public void onClick(View v) {
			TableRow row = (TableRow) v.getParent();
			Contact contact = mApp.getContactById((String)row.getTag());
			mEditedParticipant = mAdded.get(contact);

			showDialog(DATE_DIALOG_ID);
		}
	}

	public class TimeOnClickListener implements OnClickListener {

		public void onClick(View v) {
			TableRow row = (TableRow) v.getParent();
			Contact contact = mApp.getContactById((String)row.getTag());
			mEditedParticipant = mAdded.get(contact);

			showDialog(TIME_DIALOG_ID);
		}
	}

	public class TextOnClickListener implements OnClickListener {

		public void onClick(View v) {
			TableRow row = (TableRow) v.getParent();
			Contact contact = mApp.getContactById((String)row.getTag());
			mEditedParticipant = mAdded.get(contact);

			mAdded.remove(contact);
			mRemoved.put(contact, mEditedParticipant);

			mTableView.removeView(row);
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Date date = null;
		if (mEditedParticipant != null && mEditedParticipant.getDate() != null) {
			date = mEditedParticipant.getDate();
		}

		switch (id) {
		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, mTimeSetListener,
					date.getHours(), date.getMinutes(), false);
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, date.getYear(),
					date.getMonth(), date.getDate());
		}
		return null;
	}

	// the callback received when the user "sets" the time in the dialog
	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

			Date date = mEditedParticipant.getDate();

			// get the current time
			date.setHours(hourOfDay);
			date.setMinutes(minute);
		}
	};

	// the callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			Date date = mEditedParticipant.getDate();

			date.setYear(year);
			date.setMonth(monthOfYear);
			date.setDate(dayOfMonth);
		}
	};

}
